﻿using CleverDD.Helper;
using CleverDD.Model.Communication.PLC;
using CleverDD.Model.Param;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FrameWorkDemo.Communication.PLC
{
    public partial class EditPlcAddressForm : Form
    {


        public EditPlcAddressForm(Guid plcInfoGuid)
        {
            InitializeComponent();
            InitControl();
            _plcInfoGuid = plcInfoGuid;
        }

        Guid _plcInfoGuid;
        
        private List<PlcAddressInfoEntity> _showList = new List<PlcAddressInfoEntity>();

        #region 变量定义
        //避免修改参数时，直接在程序中生效，编辑类里面统一新建一个对象去修改
        private List<PlcAddressInfoEntity> _plcAddressInfoList = new List<PlcAddressInfoEntity>();
        private int _comIndex;
        private string _currentGuid;
        #endregion

        #region 初始化
        public void InitControl()
        {
            this.MaximizeBox = false;
            this.MinimizeBox = false;

            this.StartPosition = FormStartPosition.CenterParent;

            ListView.FullRowSelect = true;
            ListView.View = View.Details;  // 设置视图为 Details 模式以显示列标题
            ListView.Dock = DockStyle.Fill;
            // 添加四列标题
            ListView.Columns.Add("ID", 0);
            ListView.Columns.Add("序号", 50);
            ListView.Columns.Add("名称", 100);
            ListView.Columns.Add("状态", 60);
            ListView.SelectedIndexChanged += new System.EventHandler(this.ListView_SelectedIndexChanged);
        }


        private void EditPlcAddressForm_Load(object sender, EventArgs e)
        {
            LoadPlcAddressInfoList();

            List<ParamInfo> paramList = new List<ParamInfo>
            {
                new ParamInfo("序号"),
                new ParamInfo("名称"),
                new ParamInfo("地址"),
                
            };
            ParamInfo typeParam = new ParamInfo
            {
                LabelName = "数据类型",
                ParamType = ParamType.ComboBox,
                ValueList = new List<string>(Enum.GetNames(typeof(PlcDataType))),
            };
            paramList.Add(typeParam);
            paramList.Add(new ParamInfo("数据长度"));
           
            ParamInfo typeParam2 = new ParamInfo
            {
                LabelName = "字符编码",
                ParamType = ParamType.ComboBox,
                ValueList = new List<string>(Enum.GetNames(typeof(EncodingType))),
            };
            paramList.Add(typeParam2);

            ParamInfo typeParam3 = new ParamInfo
            {
                LabelName = "状态",
                ParamType = ParamType.ComboBox,
                ValueList = new List<string>(Enum.GetNames(typeof(PlcState))),
            };
            paramList.Add(typeParam3);

            paramList.Add(new ParamInfo("默认值"));
            BasicParamUc.InitControl(paramList);


            if (ListView.Items.Count > 0)
            {
                ListView.Items[0].Selected = true;
                ListView.EnsureVisible(0); // 确保第一行可见
                ListView.Focus();          // 设置焦点以便显示选择状态
            }
        }

        #endregion

        #region 控件方法

        private void ListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            List<string> list = new List<string>();
            if (ListView.SelectedItems.Count == 0)
            {
                _currentGuid = "";
                for (int i = 0; i < 7; i++)
                {
                    list.Add("");
                }
                BasicParamUc.InitData(list);
                return;
            }
            _comIndex = ListView.SelectedIndices[0];
            _currentGuid = this.ListView.Items[_comIndex].SubItems[0].Text.Trim();

            //根据guid找到选中的对象
            PlcAddressInfoEntity selectedItem = _plcAddressInfoList.FirstOrDefault(p => p.Guid == Guid.Parse(_currentGuid));
            //将选中对象的属性转成字符串的形式，传给详情界面 
            if (selectedItem != null)
            {
                list.Add(selectedItem.SortIndex + "");
                list.Add(selectedItem.Name + "");
                list.Add(selectedItem.Address + "");
                list.Add(selectedItem.DataType + "");
                list.Add(selectedItem.Length + "");
                list.Add(selectedItem.EncodingType + "");
                list.Add(selectedItem.State + "");
                list.Add(selectedItem.DefaultValue + "");
            }

            BasicParamUc.InitData(list);

        }


        private void NewBtn_Click(object sender, EventArgs e)
        {

            BasicParamUc.GetAllValue();
            PlcAddressInfoEntity plcAddressInfo = new PlcAddressInfoEntity();
            plcAddressInfo.Guid = Guid.NewGuid();
            plcAddressInfo.PlcInfoGuid = _plcInfoGuid;


            int.TryParse(BasicParamUc.ParamList[0].NewValue, out int sortIndex);
            plcAddressInfo.SortIndex = _plcAddressInfoList.Any()
                ? Math.Max(sortIndex, _plcAddressInfoList.Max(t => t.SortIndex)+1)
                : sortIndex;

            plcAddressInfo.Name = BasicParamUc.ParamList[1].NewValue;
            plcAddressInfo.Address = BasicParamUc.ParamList[2].NewValue;
            Enum.TryParse(BasicParamUc.ParamList[3].NewValue, out plcAddressInfo.DataType);
            int.TryParse(BasicParamUc.ParamList[4].NewValue, out plcAddressInfo.Length);
            Enum.TryParse(BasicParamUc.ParamList[5].NewValue, out plcAddressInfo.EncodingType);
            Enum.TryParse(BasicParamUc.ParamList[6].NewValue, out plcAddressInfo.State);
            plcAddressInfo.DefaultValue = BasicParamUc.ParamList[7].NewValue;


            if ("".Equals(plcAddressInfo.Name))
            {
                MessageBox.Show("名称不能为空");
                return;
            }

            bool sameNameFlag = _plcAddressInfoList.Any(obj => obj.Name == plcAddressInfo.Name);

            if (sameNameFlag)
            {
                MessageBox.Show("名称不能相同");
                return;
            }

            _plcAddressInfoList.Add(plcAddressInfo);
            SavaPlcAddressInfoList();

        }

        private void SaveBtn_Click(object sender, EventArgs e)
        {
            if ("".Equals(_currentGuid))
            {
                MessageBox.Show("未选中数据");
                return;
            }
            BasicParamUc.GetAllValue();
            foreach (var plcAddressInfo in _plcAddressInfoList)
            {
                if (plcAddressInfo.Guid == Guid.Parse(_currentGuid))
                {
                    int.TryParse(BasicParamUc.ParamList[0].NewValue, out plcAddressInfo.SortIndex);
                    plcAddressInfo.Name = BasicParamUc.ParamList[1].NewValue;
                    plcAddressInfo.Address = BasicParamUc.ParamList[2].NewValue;
                    Enum.TryParse(BasicParamUc.ParamList[3].NewValue, out plcAddressInfo.DataType);
                    int.TryParse(BasicParamUc.ParamList[4].NewValue, out plcAddressInfo.Length);
                    Enum.TryParse(BasicParamUc.ParamList[5].NewValue, out plcAddressInfo.EncodingType);
                    Enum.TryParse(BasicParamUc.ParamList[6].NewValue, out plcAddressInfo.State);
                    plcAddressInfo.DefaultValue = BasicParamUc.ParamList[7].NewValue;
                    break;
                }
            }
            SavaPlcAddressInfoList();
        }

        private void DelBtn_Click(object sender, EventArgs e)
        {
            _plcAddressInfoList.RemoveAll(p => p.Guid == Guid.Parse(_currentGuid));
            SavaPlcAddressInfoList();
        }

        private void RefreshBtn_Click(object sender, EventArgs e)
        {
            LoadPlcAddressInfoList();
        }

        #endregion

        #region 主要方法

        public void SavaPlcAddressInfoList()
        {
            StaticTool.SavaPlcAddressInfoList(_plcAddressInfoList);
            LoadPlcAddressInfoList();
        }


        public void LoadPlcAddressInfoList()
        {
            _plcAddressInfoList = StaticTool.LoadPlcAddressInfoList();
            _showList = _plcAddressInfoList.Where(plcInfo => plcInfo.PlcInfoGuid == _plcInfoGuid).ToList();
            this.ListView.Items.Clear();
            foreach (var item in _showList)
            {
                ListViewItem lvi = new ListViewItem
                {
                    Text = item.Guid + ""
                };
                lvi.SubItems.Add(item.SortIndex + "");
                lvi.SubItems.Add(item.Name);
                lvi.SubItems.Add(item.State+"");
                this.ListView.Items.Add(lvi);
            }
        }

        #endregion

        
    }
}
